package com.approval.controller;

import com.approval.dto.CompleteTaskRequest;
import com.approval.dto.Result;
import com.approval.dto.StartProcessRequest;
import com.approval.entity.ApprovalInstance;
import com.approval.service.ApprovalInstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 审批实例控制器
 */
@RestController
@RequestMapping("/instances")
public class InstanceController {
    
    @Autowired
    private ApprovalInstanceService instanceService;
    
    @PostMapping("/start")
    public Result<ApprovalInstance> startProcess(@Valid @RequestBody StartProcessRequest request) {
        ApprovalInstance instance = instanceService.startProcess(request);
        return Result.success(instance);
    }
    
    @PostMapping("/complete")
    public Result<Void> completeTask(@Valid @RequestBody CompleteTaskRequest request) {
        instanceService.completeTask(request);
        return Result.success();
    }
    
    @GetMapping("/my-applications")
    public Result<List<ApprovalInstance>> getMyApplications() {
        List<ApprovalInstance> instances = instanceService.getMyApplications();
        return Result.success(instances);
    }
    
    @GetMapping("/my-tasks")
    public Result<List<Map<String, Object>>> getMyTasks() {
        List<Map<String, Object>> tasks = instanceService.getMyTasks();
        return Result.success(tasks);
    }
    
    @GetMapping("/my-completed-tasks")
    public Result<List<Map<String, Object>>> getMyCompletedTasks() {
        List<Map<String, Object>> tasks = instanceService.getMyCompletedTasks();
        return Result.success(tasks);
    }
    
    @GetMapping("/{id}")
    public Result<Map<String, Object>> getInstanceDetail(@PathVariable Long id) {
        Map<String, Object> detail = instanceService.getInstanceDetail(id);
        return Result.success(detail);
    }
    
    @PostMapping("/{id}/cancel")
    public Result<Void> cancelInstance(@PathVariable Long id) {
        instanceService.cancelInstance(id);
        return Result.success();
    }
    
    @PostMapping("/task/{taskId}/transfer")
    public Result<Void> transferTask(
            @PathVariable Long taskId,
            @RequestParam Long targetUserId,
            @RequestParam(required = false) String reason) {
        instanceService.transferTask(taskId, targetUserId, reason != null ? reason : "工作需要");
        return Result.success();
    }
    
    @PostMapping("/batch-complete")
    public Result<Void> batchCompleteTask(@RequestBody Map<String, Object> request) {
        List<Long> taskIds = (List<Long>) request.get("taskIds");
        String action = (String) request.get("action");
        String comment = (String) request.get("comment");
        
        instanceService.batchCompleteTask(taskIds, action, comment);
        return Result.success();
    }
}

